#include "ScriptClient.h"
#include "TcpClient.h"
#include "RTDEProtocol.h"
#include "RTDEUtility.h"
#include <iostream>
#include <fstream>

namespace CURCONTROL {

ScriptClient::ScriptClient()
{

}

ScriptClient::~ScriptClient()
{

}

bool ScriptClient::Connect(const std::string &robotIp)
{
    bool rtn = false;
    if(BaseClient::Connect(robotIp, PRIMARY_PORT, true)){
        rtn = true;
    }
    this->StartReceiveThread(
                std::bind(&ScriptClient::ReceiveCallback, this, std::placeholders::_1));
    return false;
}

bool ScriptClient::SendScript(const std::string &fileName)
{
    if(!IsConnected()){
        return false;
    }
    if (!LoadScript(fileName))
    {
        return false;
    }

    if (!rtdeScript_.empty())
    {
        std::string script = "def rtde_control():\n";
        script += rtdeScript_;
        script += "end\n";
        if(this->tcpClient_->Write(script)){
//            std::string msg{"send rtde_script successful"};
//            RTDEUtility::PrintStr(msg);
//            logger::get(logger::CURCTL_LOG)->info(msg);
        }else{
            std::string str{"Failed to send rtde control script to the controller"};
            RTDEUtility::PrintStr(str);
            return false;
        }
    }
    else
    {
        std::string str{"控制脚本内容为空!!!"};
        RTDEUtility::PrintStr(str);
        RTDEUtility::PrintStr(str);
        return false;
    }

    return true;
}

bool ScriptClient::SendCommand(const std::string &command)
{
    if(!IsConnected()){
        return false;
    }
    if(command.empty()){
        return false;
    }
    if(this->tcpClient_->Write(command)){
//        std::string str{"ScriptClient::SendCommand:\n"};
//        str += command;
//        RTDEUtility::PrintStr(str);
//        logger::get(logger::CURCTL_LOG)->info(str);
        return true;
    }else{
        std::string str{"ScriptClient::SendCommand:\n"};
        str += command;
        RTDEUtility::PrintStr(str);
        RTDEUtility::PrintStr(str);
        return false;
    }
}

void ScriptClient::Clear()
{

}

void ScriptClient::ReceiveCallback(std::vector<uint8_t> &bytes)
{
    bytes.clear();// 暂未解析数据
}

bool ScriptClient::LoadScript(const std::string &fileName)
{
    // 已经加载过了直接返回
    if(!rtdeScript_.empty()){
        return true;
    }
    // Read in the UR script file
    std::ifstream file(fileName.c_str());
    if (file)
    {
        file.seekg(0, std::ios::end);
        rtdeScript_.reserve(file.tellg());
        file.seekg(0, std::ios::beg);
        // Do not remove the redundant parentheses, this is to avoid the most vexing parse!
        rtdeScript_.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
        return true;
    }
    else
    {
        std::string str{"There was an error reading the provided script file:"};
        str.append(fileName);
        std::cerr << str << std::endl;
        RTDEUtility::PrintStr(str);
        return false;
    }
}

}// namespace CURCONTROL

